package com.qingyun.common.annotation;


import org.springframework.util.StringUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.util.regex.Pattern;

@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {IsPhoneValidation.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
public @interface IsPhone {

    String message() default "手机号格式错误";

    String value() default "手机号格式错误";

    Class<?>[] group() default {};

    Class<? extends Payload>[] payload() default {};
}

class IsPhoneValidation implements ConstraintValidator<IsPhone, String> {

    private static final Pattern PATTERN= Pattern.compile( "^1[345678]\\d{9}$");

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isEmpty(value)) {
            return false;
        } else {
            return isPhone(value);
        }
    }

    @Override
    public void initialize(IsPhone constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    /**
     * 验证手机号
     */
    public static boolean isPhone(String iphone){
        if (StringUtils.isEmpty(iphone)) {
            return false;
        } else {
            return PATTERN.matcher(iphone).matches();
        }
    }
}
